package org.zjt.scala.book


import scala.collection.JavaConverters
import scala.collection.JavaConverters.bufferAsJavaList
import scala.collection.mutable.ArrayBuffer
import scala.util.Sorting

/**
  *
  * Description:
  *
  *     数组    Array
  *     可变数组  ArrayBuffer : += 、 ++= 、insert(前面)、remove 、trim 删除、移除 、yield 、convert java collection
  *
  * @author juntao.zhang
  *         Date: 2018-06-27 下午4:46
  * @see
  */
class Chapter3 {




}


object Chapter3 extends App {


  /** 不可变长度数组 **/
  var array = Array("sss","bbbb")
  println(array.mkString(","))
  println(array(1))
  println(array.apply(0))


  array = new Array[String](3)
  array(1) = "SSS"
  array(2) = "DDD"
  println(array.mkString(","))


  /** 可变长度数组缓存 **/
  var arrayBuffer = ArrayBuffer[Int]()
  arrayBuffer += 1
  arrayBuffer ++= Array(2,3)
  arrayBuffer += (2,3,2)
  println(arrayBuffer.mkString(","))


  /** 移除前后各两个 **/
  arrayBuffer.trimStart(2)
  arrayBuffer.trimEnd(2)
  println(arrayBuffer.mkString(","))


  /** index 之前插入一个、多个元素  **/
  arrayBuffer.insert(1,2)
  arrayBuffer.insert(2,2,3,34)
  println(arrayBuffer.mkString(","))

  arrayBuffer.remove(2)
  println(arrayBuffer.mkString(","))
  println(arrayBuffer.toArray.mkString(","))


  /** 迭代器遍历、索引遍历 **/
  for(item <- arrayBuffer if item % 2 == 0){
    print(item)
  }


  for(item <- 0 until arrayBuffer.length if item % 2 == 0){
    print(item,arrayBuffer(item))
  }


  /** yield 转换  **/
  val newArray = for(item <- 0 until arrayBuffer.length if item % 2 == 0) yield arrayBuffer(item)
  println(newArray.mkString(","))

  val newArray2 = arrayBuffer.filter(_ % 2 == 0).map( 2 * _ )
  println(newArray2.mkString(","))


  /** for each 守卫 **/
  val array3 = Array(1,2,32,3,-1,2,-3,32,-43,2)
  var first = true
  val array4 = for(item <- array3 if item > 0 || first) yield { if(item < 0) first = false; item}
  println(array4.mkString(","))


  println(s"sum ",array4.sum)
  println(s"max ",array4.max)
  println(s"min ",array4.min)
  println(s"sorted ${array4.sorted.mkString(",")} ")
  Sorting.quickSort(array3)
  println(array3.mkString("<",",",">"))
  println(s"2 的个数: ${array3.count(i => i == 2)}")

  /** scala array convert java list **/
  val arrayBuffer2 = ArrayBuffer[String]("222","wwww","sgd","tyuwte")
  val list = bufferAsJavaList(arrayBuffer2)
  println(s"ArrayBuffer -> (JAVA)List : ${String.join(",",list)}")


  /** scala immutable map convert java map **/
  val map = Map("key1" -> "value1","key2" -> "value2","key3" -> "value3")
  val jMap = JavaConverters.mapAsJavaMap(map)
  for(key <- JavaConverters.asScalaSet(jMap.keySet())){
    println(s"key = ${key} value =${jMap.get(key)}")
  }
}
